package org.activiti.process;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;

import org.apache.log4j.Logger;

public class CekaniNaDokonceniRozdeleni implements JavaDelegate {

    private static Logger logger = Logger.getLogger("CekaniNaDokonceniRozdeleni");

    @Override
    public void execute(DelegateExecution arg0) throws Exception {
        String[] ids = (String[]) arg0.getVariable("ids");
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = processEngine.getHistoryService();
        arg0.setVariable("result", 0);
        logger.info("Thread active count " + Thread.activeCount());     
        logger.info("Thread " + Thread.currentThread().getId());

        for (String processId : ids) {
            if (historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult().getDurationInMillis() == null) {
                logger.info(arg0.getProcessInstanceId() + " subprocesses not finished ");
                return;
            }
        }     
        logger.info("All subprocesses finished for " + arg0.getProcessInstanceId());
        arg0.setVariable("result", 1);
    }

}
